package android.cmpe451.group7.activity;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Type;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;

import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.app.ProgressDialog;
import android.cmpe451.group7.activity.R;

import android.cmpe451.group7.dbrequest.RetrieveJSONTask;
import android.cmpe451.group7.dbrequest.SimpleCommentTask;
import android.cmpe451.group7.dbrequest.SimplePlaceTask;
import android.cmpe451.group7.dbrequest.WebServiceResponse;
import android.cmpe451.group7.entity.Comment;
import android.cmpe451.group7.entity.Multimedia;
import android.cmpe451.group7.entity.Place;
import android.cmpe451.group7.entity.Tag;
import android.cmpe451.group7.entity.User;
import android.cmpe451.group7.util.Aes;
import android.cmpe451.group7.util.GlobalVariables;
import android.cmpe451.group7.util.RequestURLCreator;
import android.cmpe451.group7.util.SessionManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Shows details of a place. It shows the place's like count, picture and map coordinates.
 * Via this activity, one can access comments related to the place
 * and add new comments and pictures.
 */
public class PlaceDetailActivity extends FragmentActivity {

	// HttpParams params = new BasicHttpParams();
	// params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
	// HttpVersion.HTTP_1_1);
	// mHttpClient = new DefaultHttpClient(params);
	private File image;
	private Button uploadButton;
	private Bitmap bitmap;
	private Button selectImageButton;

	private static String upLoadServerUri = "http://www.androidexample.com/media/UploadToServer.php";
	private static int RESULT_LOAD_IMAGE = 1;
	public final static String _MESSAGE = "com.example.ourcity_android.MESSAGE";
	private String placeID;
	private ListView listView;
	private CommentArrayAdapter adapter;
	private Place place;

	String userID = null;
	String password = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_place_detail);

		SessionManager session = new SessionManager(getApplicationContext());
		HashMap<String, String> userIdDetails = session.getUserIdDetails();
		userID = userIdDetails.get(SessionManager.KEY_USERID);
		password = userIdDetails.get(SessionManager.KEY_PASSWORD);

		Intent intent = getIntent();
		placeID = intent.getStringExtra(SearchResultsActivity.EXTRA_MESSAGE);
		place = (Place) intent.getExtras().getSerializable("place");

		TextView placeText = (TextView) findViewById(R.id.place_name);
		placeText.setText(place.getPlaceName());
		TextView cityText = (TextView) findViewById(R.id.city_name);
		cityText.setText(place.getCity());
		TextView countryText = (TextView) findViewById(R.id.countryName);
		countryText.setText(place.getCountry());
		TextView likeText = (TextView) findViewById(R.id.like_text);
		likeText.setText(Integer.toString(place.getLikeCount()));

		// addition of the comments to the details page
		listView = (ListView) findViewById(R.id.commentsListView);
		String url = RequestURLCreator.createGetCommentsURL(Long
				.parseLong(placeID));
		new CommentTask(this).execute(url);

	}

	/**
	 * Likes the place and increments the like count.
	 * @param view
	 * @throws InvalidKeyException
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 */
	public void likeAction(View view) throws InvalidKeyException,
			UnsupportedEncodingException, NoSuchAlgorithmException,
			NoSuchPaddingException, IllegalBlockSizeException,
			BadPaddingException {
		Intent intent = getIntent();
		String placeID = intent
				.getStringExtra(SearchResultsActivity.EXTRA_MESSAGE);
		String url = String.format(GlobalVariables.like_Action_URL, placeID,
				userID,
				URLEncoder.encode(Aes.encryptPassword(password), "ISO-8859-1"));

		WebServiceResponse<Place> r = null;
		try {
			r = new SimplePlaceTask().execute(url).get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		if (r != null) {
			if (r.success == 1) {
				TextView likeText = (TextView) findViewById(R.id.like_text);
				int likeCount = Integer.parseInt((String) likeText.getText());
				likeCount++;
				likeText.setText(Integer.toString(likeCount));
			} else {
				Toast.makeText(this, "You have liked before",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	
	/**
	 * Add comments to the place and comment adapter.
	 * @param view
	 * @throws InvalidKeyException
	 * @throws UnsupportedEncodingException
	 * @throws NoSuchAlgorithmException
	 * @throws NoSuchPaddingException
	 * @throws IllegalBlockSizeException
	 * @throws BadPaddingException
	 */
	public void addComment(View view) throws InvalidKeyException,
			UnsupportedEncodingException, NoSuchAlgorithmException,
			NoSuchPaddingException, IllegalBlockSizeException,
			BadPaddingException {
		SessionManager session = new SessionManager(getApplicationContext());
		session.checkLogin();

		Intent intent = getIntent();
		String placeID = intent
				.getStringExtra(SearchResultsActivity.EXTRA_MESSAGE);

		EditText commentText = (EditText) findViewById(R.id.commentBox);
		String comment = commentText.getText().toString();
		comment = comment.replaceAll(" ", "+");

		String url = String.format(GlobalVariables.add_comments_URL, placeID,
				userID,
				URLEncoder.encode(Aes.encryptPassword(password), "ISO-8859-1"),
				comment);

		try {
			new SimpleCommentTask().execute(url).get();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.place_detail, menu);
		return true;
	}

	/**
	 * Creates an comment array adapter that holds all comments with their
	 * text, description and image.
	 *
	 */
	private class CommentArrayAdapter extends ArrayAdapter<Comment> {
		public CommentArrayAdapter(Context context, int textViewResourceId,
				List<Comment> dataList) {
			super(context, textViewResourceId, dataList);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) super.getContext()
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View rowView = inflater.inflate(R.layout.comment_adapter, parent,
					false);
			TextView commentTextView = (TextView) rowView
					.findViewById(R.id.commentText);
			TextView descTextView = (TextView) rowView
					.findViewById(R.id.commentDescription);
			ImageView imageView = (ImageView) rowView
					.findViewById(R.id.commentIcon);

			Comment comment = super.getItem(position);
			User user = comment.getUser();
			String desc = String.format("%s %s - %s", user.getName(),
					user.getSurname(), comment.getDate());

			commentTextView.setText(comment.getComment());
			descTextView.setText(desc);
			//imageView.setImageResource(R.drawable.placecomment);

			return rowView;
		}
	}

	/* ### Async task definitions ############### */

	/**
	 * Adds comment to the adapter.
	 *
	 */
	private class CommentTask extends RetrieveJSONTask<Comment> {
		ProgressDialog progressDialog;

		public CommentTask(Activity activity) {
			super(activity);
		}

		@Override
		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(activity, "",
					"getting comments...");
		}

		@Override
		protected WebServiceResponse<Comment> doInBackground(String... params) {
			Type type = new TypeToken<WebServiceResponse<Comment>>() {
			}.getType();
			return super.doInBackground(type, params);
		}

		@Override
		protected void onPostExecute(WebServiceResponse<Comment> wsr_comment) {
			progressDialog.dismiss();

			adapter = new CommentArrayAdapter(activity,
					android.R.layout.simple_list_item_1, gsonObject.data);
			adapter.notifyDataSetChanged();
			listView.setAdapter(adapter);
		}
	}

	/**
	 * Shows the location of the place on the map.
	 */
	public void mapAction(View view) {
		Intent intent = new Intent(getApplicationContext(), MapActivity.class);
		intent.putExtra("longitude", String.valueOf(place.getLongitude()));
		intent.putExtra("latitude", String.valueOf(place.getLatitude()));
		intent.putExtra("placeName", place.getPlaceName());

		String tags = "Tags : ";

		if (place.getTags() != null) {
			for (Tag tag : place.getTags()) {
				tags += tag.getTagName() + ",";
			}
			tags = tags.substring(0, tags.length() - 1);
		}

		intent.putExtra("tags", tags);
		startActivity(intent);
	}

	/**
	 * Uploads picture.
	 * @param view
	 */
	public void pictureAction(View view) {
		Intent intent = new Intent(getApplicationContext(),
				PictureActivity.class);

		List<Integer> placeMultimediaIds = new ArrayList<Integer>();
		for (Multimedia id : place.getMultimedia())
			placeMultimediaIds.add((int) id.getMultimediaID());

		intent.putIntegerArrayListExtra("multimediaIds",
				(ArrayList<Integer>) placeMultimediaIds);
		startActivity(intent);
	}

	/**
	 * Selects picture for upload.
	 * @param view
	 */
	public void selectPicture(View view) {
		Intent i = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

		startActivityForResult(i, RESULT_LOAD_IMAGE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			try {
				new UploadImageTask(data).execute("asd");
				Intent intent = getIntent();
				finish();
				startActivity(intent);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
		}
	}
	
	/**
	 * Upload image task.
	 *
	 */
	private class UploadImageTask extends AsyncTask<String, String, String>{
		
		Intent data;
		
		public UploadImageTask(Intent dataFromImage) {
			data = dataFromImage;
			// TODO Auto-generated constructor stub
		}

		@Override
		protected String doInBackground(String... arg0) {
			// TODO Auto-generated method stub
			try{
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			String pictureExtension = "image/jpeg";
			if(picturePath.endsWith("jpg"))
				pictureExtension = "image/jpg";
			else if(picturePath.endsWith("jpeg"))
				pictureExtension = "image/jpeg";
			else if(picturePath.endsWith("png"))
				pictureExtension = "image/png";
			else if(picturePath.endsWith("gif"))
				pictureExtension = "image/gif";
			
			File f = new File(picturePath);
			FileBody fo = new FileBody(f);
			HttpClient client = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://titan.cmpe.boun.edu.tr:8086/ourcity-ws/webservice/place/uploadImage");

			MultipartEntity multipartEntity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);

			multipartEntity.addPart("placeID", new StringBody(placeID));
			multipartEntity.addPart("userID", new StringBody(userID));
			multipartEntity.addPart("password", new StringBody(URLEncoder.encode(Aes.encryptPassword(password), "ISO-8859-1")));
			multipartEntity.addPart("fileExtension", new StringBody(pictureExtension));
			multipartEntity.addPart("image", fo);
			
			httppost.setEntity(multipartEntity);
			HttpResponse response = client.execute(httppost);
			} catch(Exception e){
				e.printStackTrace();
			}
			return null;
		}
		
	}
}
